<template>
  <div style="width: 100%;position: relative">
    <div id="container" class="map"></div>
    <div class="search-box">
      <el-select v-if="isSearch" v-model="address" clearable placeholder="请输入关键词" :remote-method="remoteMethod"
                 filterable remote @change="currentSelect" class="one-text" size="default">
        <el-option v-for="(item, index) in areaList" :key="index" :label="item.district + item.name"
                   :value="item.district + item.name">
          <span>{{ item.district }}</span> <span>{{ item.name }}</span>
        </el-option>
      </el-select>
    </div>
  </div>
</template>

<script setup name="x-address-map">
import { reactive, ref, toRefs, onMounted, nextTick, defineProps } from 'vue';
let TMap = window.TMap;
const props = defineProps({
  addressClick: Function,
  isSearch: {
    type: Boolean,
    default: false
  }
})

onMounted(() => {
  nextTick(() => {
    initMap()
  })
})

const state = reactive({
  placeSearch: null,
  autoComplete: null,
  marker: null,
  form: {
    address: '',
    lng: '',
    lat: '',
  },
  areaList: [],
  address: ''
})

const { areaList, address } = toRefs(state)
let map = null;
const initMap = (center) => {
  if(map == null) {
    map = new TMap.Map(document.getElementById('container'), {
      zoom: 15, // 设置地图缩放级别
      viewMode: '2D',
    });
  }

  setCenter(center)
}

const setCenter = (data) => {
  let lat = 39.910506;
  let lng = 116.39926431433355;
  if(! Helper.emptyJson(data)) {
    lat = data.lat;
    lng = data.lng;
  }
  const center = new TMap.LatLng(lat, lng)
  map.setCenter(center);//坐标为天安门
}

function setMapMarker(pos) {
  if (pos.lng == '' && pos.lat == '') {
    return
  }

  let center = new TMap.LatLng(Number(pos.lat), Number(pos.lng));
  state.marker = new TMap.MultiMarker({
    map: map,
    styles: {
      // 点标记样式
      marker: new TMap.MarkerStyle({
        width: 20, // 样式宽
        height: 30, // 样式高
        anchor: { x: 10, y: 30 }, // 描点位置
      }),
    },
    geometries: [
      // 点标记数据数组
      {
        // 标记位置(纬度，经度，高度)
        position: center,
        id: 'marker',
      },
    ],
  });
}

function removeMarker() {
  if (state.marker) {
    state.marker.setMap(null);
    state.marker = null;
  }
}

function remoteMethod(query) {
  if (query !== '') {
    setTimeout(() => {
      state.autoComplete.search(query, (status, result) => {
        state.areaList = result.tips
      })
    }, 500)
  } else {
    state.areaList = []
  }
}
function currentSelect(val) {
  if (!val) {
    return
  }
  toGetCoordinate(val)
}



function fixed(lng, lat) {
  let pos = {lng: lng, lat: lat};
  nextTick(() => {
    initMap(pos)
    removeMarker()
    setMapMarker(pos)
    state.form.lng = lng
    state.form.lat = lat
  })
}

function toGetCoordinate(address) {
  return new Promise((resolve, reject) => {
    state.address = address;
    if(Helper.empty(address)) {
      reject();
      return;
    }
    let geocoder = new TMap.service.Geocoder();
    geocoder.getLocation({address}).then(data => {
      let status = data.status;
      let message = data.message;
      let result = data.result;

      if (status === 0 && message === 'query ok') {

        let lng = result.location.lng;
        let lat = result.location.lat;

        state.form.lng = lng;
        state.form.lat = lat;
        state.form.address = result.title

        let pos = {lng: lng, lat: lat};
        initMap(pos)
        removeMarker()
        setMapMarker(pos)
        props.addressClick(result, lng, lat);
        resolve({result, lng, lat})
      }
    })
  })
}

// 暴露方法
defineExpose({
  fixed,
  toGetCoordinate
});
</script>



<style scoped lang="less">
.map {
  width: 100%;
  height: 400px;
}

.search-box {
  position: absolute;
  z-index: 9;
  top: 20px;
  left: 20px;

  ::v-deep(.el-select) {
    width: 640px !important;
    border-radius: 50px;
    overflow: hidden;

    .el-input__wrapper {
      border-radius: 50px;
    }
  }
}
</style>
